<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Config;
use think\Cache;
use think\Cookie;
use think\Hook;
use think\Session;
use think\Validate;
use app\common\library\Sms;

/**
 * 会员中心
 */
class User extends Frontend
{

    protected $noNeedLogin = ['login', 'register','pay_verify','qqlogin','mndl','register_v','agent_v'];
    protected $noNeedRight = ['*'];
    protected $layout = 'default';

    public function _initialize()
    {
        parent::_initialize();
        $auth = $this->auth;

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

        $ucenter = get_addon_info('ucenter');
        if ($ucenter && $ucenter['state']) {
            include ADDON_PATH . 'ucenter' . DS . 'uc.php';
        }

        //监听注册登录注销的事件
        Hook::add('user_login_successed', function ($user) use ($auth) {
            $expire = input('post.keeplogin') ? 30 * 86400 : 0;
            Cookie::set('uid', $user->id, $expire);
            Cookie::set('token', $auth->getToken(), $expire);
        });
        Hook::add('user_register_successed', function ($user) use ($auth) {
            Cookie::set('uid', $user->id);
            Cookie::set('token', $auth->getToken());
        });
        Hook::add('user_delete_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
        Hook::add('user_logout_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });

        $info = '会员中心';
        $this->assign('info',$info);

        $orderCount = $this->CommonPayOrderModel->where(['uid'=>$this->auth->id])->count();
        $orderMoney = $this->CommonPayOrderModel->where(['uid'=>$this->auth->id])->sum('money');
        $this->assign([
            'orderCount'=>$orderCount,
            'orderMoney'=>$orderMoney,
        ]);
$str = <<<str
<html lang="zh-cn">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>请完成操作</title>
<link href="/assets/css/bootstrap.min.css" rel="stylesheet"/>
<style type="text/css">
.qr-text {padding: 30px;margin: 5px 0;background-color: #FDFDCA;border-radius: 3px;border: 1px solid #EEEEEE;word-wrap: break-word;word-break: break-all;}
</style>
</head>
<body>
<br>
<div class="col-xs-12 col-sm-10 col-md-8 col-lg-6 center-block" style="float: none;">
<div class="panel panel-default">
<div class="panel-heading" style="text-align: center;"><h3 class="panel-title">
完善你的用户信息
</div>
<div class="list-group" style="text-align: center;">
<div class="list-group-item list-group-item-info">谨慎填写手机号用户名等 保存后不可更改</div>
<div class="list-group-item">
<form class="form-horizontal" method="POST" action="/index/user/ch">
<div class="item form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="mobile">手机号码<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input class="form-control col-md-7 col-xs-12" name="mobile" id="mobile" type="text" >
</div>
</div>
<div class="item form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="email">你的邮箱<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input class="form-control col-md-7 col-xs-12" name="email" id="email" type="text" >
</div>
</div>
<div class="item form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="username">用户名<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input class="form-control col-md-7 col-xs-12" name="username" id="username" type="text" >
</div>
</div>
<div class="item form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="password">密码<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input class="form-control col-md-7 col-xs-12" name="password" id="password" type="text" >
</div>
</div>
<div class="item form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="qq">QQ号码<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input class="form-control col-md-7 col-xs-12" name="qq" id="qq" type="text" >
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-3">
<button type="submit" class="btn btn-success">保存资料</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
str;
//彩虹迁移过来的数据
        $user = $this->auth->getUser();
        if ($user) {
            if ($user['api_id'].'' == $user['username'].'' && md5(md5($user['api_key']).'chchch') == $user['password']) {
                if ($this->request->action() !== 'ch') {
                    exit($str);
                }
            }
        }
    }
    
    /**
     * 数据完善
     */
    public function ch()
    {
        if (!$this->request->isPost()) exit();
        $user = $this->auth->getUser();
        if ($user['api_id'].'' !== $user['username'].'' || md5(md5($user['api_key']).'chchch') !== $user['password']) exit();
        $mobile = $this->request->post('mobile');
        $email = $this->request->post('email');
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $qq = $this->request->post('qq');
        $rule = [
            'username'  => 'require|length:3,30',
            'password'  => 'require|length:6,30',
            'email'     => 'require|email',
            'mobile'    => 'regex:/^1\d{10}$/',
            'qq'    => 'require',
        ];
        $msg = [
            'qq.require' => '请填写QQ号码',
            'username.require' => '请填写用户名',
            'username.length'  => '用户名长度3-30',
            'password.require' => '请填写密码',
            'password.length'  => '密码长度6-30',
            'email'            => '邮箱格式不正确',
            'mobile'           => '手机格式不正确',
        ];
        $data = [
            'username'  => $username,
            'password'  => $password,
            'email'     => $email,
            'mobile'    => $mobile,
            'qq'    => $qq,
        ];
        $userres = $this->CommonUserModel->where(['username'=>$username])->find();
        if ($userres) $this->error('用户名已存在');
        $userres = $this->CommonUserModel->where(['mobile'=>$mobile])->find();
        if ($userres) $this->error('手机号已存在');
        $userres = $this->CommonUserModel->where(['email'=>$email])->find();
        if ($userres) $this->error('邮箱已存在');
        $validate = new Validate($rule, $msg);
        $result = $validate->check($data);
        if (!$result) {
            $this->error(__($validate->getError()));
        }else{
            $user->username = $username;
            $user->password = md5(md5($password).'chchch');
            $user->email = $email;
            $user->mobile = $mobile;
            $user->qq = $qq;
            $user->salt = 'chchch';
            $user->save();
            $this->success();
        }
    }


    /**
     * 空的请求
     * @param $name
     * @return mixed
     */
    public function _empty($name)
    {
        $data = Hook::listen("user_request_empty", $name);
        foreach ($data as $index => $datum) {
            $this->view->assign($datum);
        }
        return $this->view->fetch('user/' . $name);
    }

    public function qqlogin(){
        $qc = new \qqlogin\QC();
        if (!$this->request->isPost()) {
            $qc->qq_callback();
        }
        $openid = $qc->get_openid();
        if (!$openid || strlen($openid)!==32) $this->error('QQ登陆失败','/index/user/login');
        if ($this->auth->id) {
            $this->CommonUserModel->where(['id'=>$this->auth->id])->update(['qq_openid'=>$openid]);
            $this->redirect('/index/user/index');
        }else{
            $this->error('请先登陆','/index/user/login');
        }
    }

    public function fqq(){
        $this->CommonUserModel->where(['id'=>$this->auth->id])->update(['qq_openid'=>'']);
        $this->success();
    }

    public function withdrawadd(){
        $user = $this->auth->getUser();
        $today = $this->CommonPayOrderModel->where(['uid'=>$this->auth->id,'status'=>1])->whereTime('createtime', 'today')->sum('realmoney');
        $money = round($user['money']-$today,2);
        if ($money.'' <= 0) $money = 0.00;
        if ($this->request->isPost()) {
            if ($user['withdraw'].'' !== '1') {
                $this->error('你被禁止提现');
            }
            if ($money.'' <= '0') {
                $this->error('账户余额不足！');
            }
            if (empty($user['withdraw_name']) || empty($user['withdraw_account']) || empty($user['withdraw_type'])) {
                $this->error('请先前往“个人资料”设置您的提现信息！');
            }
            $withdraw_need = !is_numeric(config('site.withdraw_need')) ? 10 : config('site.withdraw_need');
            $withdraw_money = !is_numeric(config('site.withdraw_money2')) ? 1 : config('site.withdraw_money2');

            $withdraw_num = !is_numeric(config('site.withdraw_num')) ? 1 : config('site.withdraw_num');
            $cache = cache(md5('withdraw'.$this->auth->id));
            if (is_numeric($cache) && $cache >= $withdraw_num) {
                $this->error('每天最多提现'.$withdraw_num.'次！');
            }
            $input_money = input('post.money');
            if ($input_money < $withdraw_need) {
                $this->error('最低提现'.$withdraw_need.'元！');
            }
            if ($input_money > $money) {
                $this->error('账户余额不足！');
            }
            if ($input_money <= round(config('site.withdraw_x'),2)) {
                $withdraw_money = config('site.withdraw_x_min_money');
            }else{
                $withdraw_money = round($input_money*$withdraw_money/100,2);
                if ($withdraw_money > config('site.withdraw_x_max_money')) {
                    $withdraw_money = config('site.withdraw_x_max_money');
                }
                if ($withdraw_money < config('site.withdraw_x_min_money')) {
                    $withdraw_money = config('site.withdraw_x_min_money');
                }
            }
            $this->CommonWithdrawModel->insert([
                'uid'=>$this->auth->id,
                'withdraw_name'=>$user['withdraw_name'],
                'withdraw_account'=>$user['withdraw_account'],
                'withdraw_type'=>$user['withdraw_type'],
                'money'=>round($input_money,2),
                'realmoney'=>round($input_money-$withdraw_money,2),
                'percent'=>$withdraw_money,
                'status'=>0,
                'back'=>'',
                'createtime'=>time(),
            ]);
            $newmoney = round($user['money'] - $input_money,2);
            $this->CommonUserModel->where(['id'=>$this->auth->id])->update(['money'=>$newmoney]);
            if (is_numeric($cache)) {
                Cache::inc(md5('withdraw'.$this->auth->id));
            }else{
                cache(md5('withdraw'.$this->auth->id),1,86400);
            }
            $this->success('提现成功','/index/user/withdraw');
        }
    }

    public function withdraw(){
        if ($this->request->isPost()) {
            $id = $this->request->post('id');
            $res = $this->CommonWithdrawModel->where(['uid'=>$this->auth->id,'id'=>$id,'status'=>2])->find();
            if (!$res) $this->error('记录不存在！');
            return json(['code'=>1,'msg'=>'OK','data'=>!empty($res['back'])?$res['back']:'无']);
        }
        $user = $this->auth->getUser();
        $today = $this->CommonPayOrderModel->where(['uid'=>$this->auth->id,'status'=>1])->whereTime('createtime', 'today')->sum('realmoney');
        $money = round($user['money']-$today,2);
        if ($money.'' <= 0) $money = 0.00;
        $list = $this->CommonWithdrawModel->where(['uid'=>$this->auth->id])->order('id desc')->paginate(15);
        $this->view->assign('list',$list);
        $this->view->assign('today',$today);
        $this->view->assign('money',$money);
        return $this->view->fetch();
    }

    /**
     * 订单管理
     */
    public function order()
    {
        $where = [];
        $where['uid'] = $this->auth->id;
        !empty(input('trade_no')) && $where['trade_no'] = (string)input('trade_no');
        !empty(input('out_trade_no')) && $where['out_trade_no'] = (string)input('out_trade_no');
        !empty(input('type')) && $where['type'] = (string)input('type');
        !empty(input('money')) && $where['money'] = (string)input('money');
        input('status') == '0' ? $where['status'] = (string)input('status') : '';
        $time1 = date('Y-m-d',strtotime('-3 Month',time()));
        $time2 = date('Y-m-d',time());
        !empty(input('startDate')) && $time1 = (string)input('startDate');
        !empty(input('endDate')) && $time2 = (string)input('endDate');
        $time2 = date('Y-m-d',strtotime('+1 day',strtotime($time2)));
        !empty(input('status')) && $where['status'] = (string)input('status');
        $res = $this->CommonPayOrderModel->where($where)->where('createtime','between time',[$time1,$time2])->order('id desc')->paginate(15,false,['query'=>request()->param()]);
        $count = $this->CommonPayOrderModel->where($where)->where('createtime','between time',[$time1,$time2])->count();
        $this->assign([
            'res'=>$res,
            'count'=>$count,
        ]);
        return $this->view->fetch();
    }

    /**
     * 会员中心
     */
    public function index()
    {
        // 结算总额
        $user = $this->auth->getUser();
        $withdrawMoney = $this->CommonWithdrawModel->where(['uid'=>$this->auth->id,'status'=>1])->sum('realmoney');
        $orderMoney2 = $this->CommonPayOrderModel->where(['uid'=>$this->auth->id])->whereTime('createtime', 'today')->sum('realmoney');
        $orderCount2 = $this->CommonPayOrderModel->where(['uid'=>$this->auth->id])->whereTime('createtime', 'today')->count();
        $todayMoney = $this->CommonPayOrderModel->where(['uid'=>$this->auth->id,'status'=>1])->whereTime('createtime', 'today')->sum('money');
        $wx = $this->CommonPayOrderModel->where(['uid'=>$this->auth->id,'type'=>'wxpay','status'=>1])->whereTime('createtime', 'today')->sum('money');
        $yesterdayMoney = $this->CommonPayOrderModel->where(['uid'=>$this->auth->id,'status'=>1])->whereTime('createtime', 'yesterday')->sum('money');
        $yesterdayMoney2 = $this->CommonPayOrderModel->where(['uid'=>$this->auth->id,'status'=>1])->whereTime('createtime', 'yesterday')->sum('realmoney');
        $qq = $this->CommonPayOrderModel->where(['uid'=>$this->auth->id,'type'=>'qqpay','status'=>1])->whereTime('createtime', 'today')->sum('money');
        $ali = $this->CommonPayOrderModel->where(['uid'=>$this->auth->id,'type'=>'alipay','status'=>1])->whereTime('createtime', 'today')->sum('money');
        $awx = $this->CommonPayOrderModel->where(['uid'=>$this->auth->id,'type'=>'wxpay','status'=>1])->whereTime('createtime', 'yesterday')->sum('money');
        $aqq = $this->CommonPayOrderModel->where(['uid'=>$this->auth->id,'type'=>'qqpay','status'=>1])->whereTime('createtime', 'yesterday')->sum('money');
        $aali = $this->CommonPayOrderModel->where(['uid'=>$this->auth->id,'type'=>'alipay','status'=>1])->whereTime('createtime', 'yesterday')->sum('money');
        if ($user['withdraw_name'] && $user['withdraw_account'] && $user['withdraw_type']) {
            $withdraw = true;
        }else{
            $withdraw = false;
        }
        $qqrate = is_numeric($user['qqpay_rate']) ? round(100-$user['qqpay_rate'],2) : round(100-config('site.default_qqpay_rate'),2);
        $wxrate = is_numeric($user['wxpay_rate']) ? round(100-$user['wxpay_rate'],2) : round(100-config('site.default_wxpay_rate'),2);
        $alirate = is_numeric($user['alipay_rate']) ? round(100-$user['alipay_rate'],2) : round(100-config('site.default_alipay_rate'),2);
        $this->view->assign([
            'qqlogin'=>($user['qq_openid']?true:false),
            'withdraw'=>$withdraw,
            'orderCount2'=>$orderCount2,
            'todayMoney'=>$todayMoney,
            'orderMoney2'=>$orderMoney2,
            'yesterdayMoney'=>round($yesterdayMoney,2),
            'yesterdayMoney2'=>round($yesterdayMoney2,2),
            'withdrawMoney'=>round($withdrawMoney,2),
            'qq'=>$qq,
            'ali'=>$ali,
            'wx'=>$wx,
            'aqq'=>$aqq,
            'aali'=>$aali,
            'awx'=>$awx,
            'qqrate'=>$qqrate,
            'wxrate'=>$wxrate,
            'alirate'=>$alirate,
        ]);
        return $this->view->fetch();
    }

    public function zzt(){
        $row = strtotime(date('Y-m-d').' 23:59:59');
        $date = [];
        for ($i=0; $i < 7; $i++) { 
            $new = strtotime('-'.$i.' Days',$row);
            $time = date('Y-m-d H:i:s',$new);
            $date[] = $time;
        }
        asort($date);
        $date = array_values($date);
        $echart = [];
        for ($i=0; $i < count($date); $i++) { 
            if (isset($date[($i-1)])) {
                $money = $this->CommonPayOrderModel->where(['uid'=>$this->auth->id,'status'=>1])->where('createtime','between time',[$date[$i-1],$date[($i)]])->sum('money');
                $count = $this->CommonPayOrderModel->where(['uid'=>$this->auth->id,'status'=>1])->where('createtime','between time',[$date[$i-1],$date[($i)]])->count();
                $echart[1][] = [
                    'x'=>strtotime($date[$i]),
                    'y'=>round($money,2),
                    'y0'=>0,
                ];
                $echart[0][] = [
                    'x'=>strtotime($date[$i]),
                    'y'=>$count,
                    'y0'=>0,
                ];
            }
        }
        return json($echart);
    }

    public function register_v(){
        $obj = new \pay\Easy();
        $url = str_replace('http://', '', config('site.pay_url'));
        $url = str_replace('https://', '', $url);
        $url = str_replace('/', '', $url);
        $url = 'http://'.$url.'/';
        $PayData = [
            'id' => config('site.pay_id'),
            'key' => config('site.pay_key'),
            'apiurl' => $url,
        ];
        $obj->config($PayData);
        $data = $obj->verify_return();
        if ($data['code'] && $data['status']=='success') {
        }else{
            $data = $obj->verify_notify();
            if ($data['code'] && $data['status']=='success') {
            }else{
                $this->error('验证失败！');
            }
        }
        $res = db('reg_log')->where(['trade_no'=>input('out_trade_no')])->find();
        if (!$res) $this->error('验证失败！');
        if ($res['status'] == 1) $this->success('已开通！请登录','/index/user/index');
        db('reg_log')->where(['trade_no'=>input('out_trade_no')])->update(['status'=>1]);
        $config = json_decode($res['config'],true);
        if (!isset($config['username']) || !isset($config['password'])) $this->error('验证失败！');
        $username = $config['username'];
        $password = $config['password'];
        $email = $config['email'];
        $mobile = $config['mobile'];
        $extends = $config['extends'];
        if ($this->auth->register($username, $password, $email, $mobile,$extends)) {
            $synchtml = '';
            ////////////////同步到Ucenter////////////////
            if (defined('UC_STATUS') && UC_STATUS) {
                $uc = new \addons\ucenter\library\client\Client();
                $synchtml = $uc->uc_user_synregister($this->auth->id, $password);
            }
            $userApi = new \app\api\controller\User();
            $userApi->replaceapi();
            $this->success(__('Sign up successful') . $synchtml, url('user/index'));
        } else {
            $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
        }
    }

    /**
     * 注册会员
     */
    public function register()
    {
        if (config("site.user_register").'' !== "1") {
            $this->error('已关闭注册！','/index/user/login');
        }
        $url = $this->request->request('url');
        if ($this->auth->id)
            $this->success(__('You\'ve logged in, do not login again'), $url);
        if ($this->request->isPost()) {
            $username = $this->request->post('username');
            $password = $this->request->post('password');
            $email = $this->request->post('email');
            $mobile = $this->request->post('mobile', '');
            $captcha = $this->request->post('captcha');
            $pid = $this->request->post('pid');
            $qq_openid = $this->request->post('qq_openid');
            $token = $this->request->post('__token__');
            $rule = [
                'username'  => 'require|length:3,30',
                'password'  => 'require|length:6,30',
                'email'     => 'require|email',
                'mobile'    => 'regex:/^1\d{10}$/',
                'captcha'   => 'require|captcha',
                '__token__' => 'token',
            ];

            $msg = [
                'username.require' => 'Username can not be empty',
                'username.length'  => 'Username must be 3 to 30 characters',
                'password.require' => 'Password can not be empty',
                'captcha.require'  => 'Captcha can not be empty',
                'captcha.captcha'  => 'Captcha is incorrect',
                'email'            => 'Email is incorrect',
                'mobile'           => 'Mobile is incorrect',
            ];
            $data = [
                'username'  => $username,
                'password'  => $password,
                'email'     => $email,
                'mobile'    => $mobile,
                'captcha'   => $captcha,
                '__token__' => $token,
            ];
            $mobile_captcha = $this->request->post('mobile_captcha');
            $result = Sms::check($mobile, $mobile_captcha, 'register');
            if (!$result)
            {
                $this->error(__('Captcha is incorrect'));
            }
            $userres = $this->CommonUserModel->where(['username'=>$username])->find();
            if ($userres) $this->error('用户名已存在');
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
            }
            $extends = [];
            $extends['withdraw'] = 0;
            if ($qq_openid && strlen($qq_openid)==32) {
                $extends['qq_openid'] = $qq_openid;
            }
            $price = config('site.register_price');
            $type = input('type');
            if (is_numeric($price) && $price.'' > '0') {
                $obj = new \pay\Easy();
                $url = str_replace('http://', '', config('site.pay_url'));
                $url = str_replace('https://', '', $url);
                $url = str_replace('/', '', $url);
                $url = 'http://'.$url.'/';
                $trade_no = date("YmdHis").mt_rand(100,999);
                $PayData = [
                    'id' => config('site.pay_id'),
                    'key' => config('site.pay_key'),
                    'apiurl' => $url,
                    'money' => $price,
                    'name' => '充值成为会员',
                    'type' => $type,
                    'notify_url' => request()->domain().'/index/User/register_v',
                    'return_url' => request()->domain().'/index/User/register_v',
                    'trade_no' => $trade_no,
                ];
                $config = json_encode(['username'=>$username, 'password'=>$password, 'email'=>$email, 'mobile'=>$mobile, 'extends'=>$extends, ]);
                db('reg_log')->insert([
                    'config'=>$config,
                    'status'=>0,
                    'trade_no'=>$trade_no,
                    'createtime'=>time(),
                ]);
                return json(['code'=>1,'msg'=>'跳转中...','data'=>$obj->submit($PayData)]);
            }
            if ($this->auth->register($username, $password, $email, $mobile,$extends)) {
                $synchtml = '';
                ////////////////同步到Ucenter////////////////
                if (defined('UC_STATUS') && UC_STATUS) {
                    $uc = new \addons\ucenter\library\client\Client();
                    $synchtml = $uc->uc_user_synregister($this->auth->id, $password);
                }
                $userApi = new \app\api\controller\User();
                $userApi->replaceapi();
                $this->success(__('Sign up successful') . $synchtml, $url ? $url : url('user/index'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER');
        if (!$url && (strtolower(parse_url($referer, PHP_URL_HOST)) == strtolower($this->request->host()))
            && !preg_match("/(user\/login|user\/register)/i", $referer)) {
            $url = $referer;
        }
        $price = config('site.register_price');
        if (is_numeric($price) && $price.'' > '0') {
            $price = round($price,2);
        }else{
            $price = false;
        }
        $this->view->assign('url', $url);
        $this->view->assign('price', $price);
        $this->view->assign('title', __('Register'));
        return $this->view->fetch();
    }

    /**
     * 会员登录
     */
    public function login()
    {
        $url = $this->request->request('url');
        if ($this->auth->id)
            $this->success(__('You\'ve logged in, do not login again'), '/index/user/index');
        if ($this->request->isPost()) {
            $account = $this->request->post('account');
            $password = $this->request->post('password');
            $keeplogin = (int)$this->request->post('keeplogin');
            $token = $this->request->post('__token__');
            $rule = [
                'account'   => 'require|length:3,50',
                'password'  => 'require|length:6,32',
                '__token__' => 'token',
            ];

            $msg = [
                'account.require'  => 'Account can not be empty',
                'account.length'   => 'Account must be 3 to 50 characters',
                'password.require' => 'Password can not be empty',
                'password.length'  => 'Password must be 6 to 30 characters',
            ];
            $data = [
                'account'   => $account,
                'password'  => $password,
                '__token__' => $token,
            ];
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return FALSE;
            }
            if ($this->auth->login($account, $password)) {
                $synchtml = '';
                ////////////////同步到Ucenter////////////////
                if (defined('UC_STATUS') && UC_STATUS) {
                    $uc = new \addons\ucenter\library\client\Client();
                    $synchtml = $uc->uc_user_synlogin($this->auth->id);
                }
                $this->success(__('Logged in successful') . $synchtml, $url ? $url : url('user/index'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER');
        if (!$url && (strtolower(parse_url($referer, PHP_URL_HOST)) == strtolower($this->request->host()))
            && !preg_match("/(user\/login|user\/register)/i", $referer)) {
            $url = $referer;
        }
        $this->view->assign('url', $url);
        $this->view->assign('title', __('Login'));
        return $this->view->fetch();
    }

    /**
     * 注销登录
     */
    function logout()
    {
        //注销本站
        $this->auth->logout();
        $synchtml = '';
        ////////////////同步到Ucenter////////////////
        if (defined('UC_STATUS') && UC_STATUS) {
            $uc = new \addons\ucenter\library\client\Client();
            $synchtml = $uc->uc_user_synlogout();
        }
        $this->success(__('Logout successful') . $synchtml, url('user/index'));
    }

    /**
     * 个人信息
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $validateurl = url('api/validate/check_sms_correct');
        $sendurl = url('api/sms/send');
        $withdraw = [
            'name'=>$user['withdraw_name'],
            'account'=>$user['withdraw_account'],
            'type'=>$user['withdraw_type'],
            'sendurl'=>$sendurl,
            'validateurl'=>$validateurl,
        ];
        $this->assignconfig('withdraw',$withdraw);
        $this->assignconfig('wxqrcode',config('site.wx_public_code'));
        $this->assignconfig('wxalert',config('site.wx_public_alert'));
        return $this->view->fetch();
    }

    /**
     * 修改密码
     */
    public function changepwd()
    {
        if ($this->request->isPost()) {
            $oldpassword = $this->request->post("oldpassword");
            $newpassword = $this->request->post("newpassword");
            $renewpassword = $this->request->post("renewpassword");
            $token = $this->request->post('__token__');
            $rule = [
                'oldpassword'   => 'require|length:6,30',
                'newpassword'   => 'require|length:6,30',
                'renewpassword' => 'require|length:6,30|confirm:newpassword',
                '__token__'     => 'token',
            ];

            $msg = [
            ];
            $data = [
                'oldpassword'   => $oldpassword,
                'newpassword'   => $newpassword,
                'renewpassword' => $renewpassword,
                '__token__'     => $token,
            ];
            $field = [
                'oldpassword'   => __('Old password'),
                'newpassword'   => __('New password'),
                'renewpassword' => __('Renew password')
            ];
            $user = $this->auth->getUser();
            $validate = new Validate($rule, $msg, $field);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return FALSE;
            }

            $ret = $this->auth->changepwd($newpassword, $oldpassword);
            if ($ret) {
                $synchtml = '';
                ////////////////同步到Ucenter////////////////
                if (defined('UC_STATUS') && UC_STATUS) {
                    $uc = new \addons\ucenter\library\client\Client();
                    $synchtml = $uc->uc_user_synlogout();
                }
                $this->success(__('Reset password successful') . $synchtml, url('user/login'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
    }

}
